import {NbGoStep} from '../NbGoStep.js';
import {waitForCondition} from '../GoUtils.js';
import {StrUtil} from '../../../utils/StrUtil.js';

function resolveFlowStatus(detail) {
    if (!detail || typeof detail !== 'object') {
        return '';
    }
    const candidates = [
        detail.flow_status,
        detail.status,
        detail.flow?.flow_status,
        detail.flow?.status,
        detail.product?.flow_status
    ];
    for (const candidate of candidates) {
        if (StrUtil.notNull(candidate)) {
            return String(candidate).toLowerCase();
        }
    }
    return '';
}

export class TestingPassedStep extends NbGoStep {
    constructor() {
        super({
            key: 'testingPassed',
            name: '测试通过',
            description: '确认测试通过状态'
        });
    }

    async shouldSkip(context) {
        const {pipeline} = context;
        const detail = await pipeline.getFlowDetail(true);
        const status = resolveFlowStatus(detail);
        if (status === 'feature_passed') {
            return {
                skip: true,
                reason: '发布单已处于 feature_passed 状态',
                metadata: {
                    status,
                    checkedAt: new Date().toISOString()
                }
            };
        }
        if (status && status !== 'feature_testing') {
            return {
                skip: true,
                reason: `当前状态为 ${status}，无需执行测试通过`,
                metadata: {
                    status,
                    checkedAt: new Date().toISOString()
                }
            };
        }
        return {skip: false};
    }

    async execute(context) {
        const {pipeline, opsClient} = context;
        const {flowId, flowType} = pipeline.getFlowIdentity();
        await opsClient.featureTestingPassed({
            id: flowId,
            type: flowType
        });
        let latestStatus = '';
        try {
            await waitForCondition(async () => {
                const detail = await pipeline.getFlowDetail(true);
                latestStatus = resolveFlowStatus(detail);
                return latestStatus === 'feature_passed';
            }, {timeoutMs: this.timeoutMs, intervalMs: 10_000});
        } catch (error) {
            throw new Error(`测试通过接口未在限定时间内完成，请手动处理 (${error.message})`);
        }
        return {
            status: latestStatus,
            finishedAt: new Date().toISOString()
        };
    }
}
